package com.cn.wanxi.servlet;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;
import com.cn.wanxi.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        1.乱码问题

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //        2.取得前台传递的值
//1.如果前端是用form表单，这里的getParameter这里面的参数对应的是页面name属性
//2.如果是ajax，这    getParameter里面的参数对应的是json对象的key值
//     let data{    "username": $("#username").val()}
//3.对于js里面的data传值对象，左边的key值 ，右边的 地址，对应的是页面的id
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String phone = req.getParameter("phone");
        String age = req.getParameter("age");
        String birthday = req.getParameter("birthday");
        String sex = req.getParameter("sex");
        String hobby = req.getParameter("hobby");
        String email = req.getParameter("email");
//        3.封装数据

        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);
        userModel.setPhone(phone);
        userModel.setAge(Tool.stringToInt(age));
        userModel.setBirthday(birthday);
        userModel.setHobby(hobby);
        userModel.setSex(sex);
        userModel.setEmail(email);
//        4.调用服务逻辑层

        IUserService iUserService = new UserServiceImpl();
//        5.得到数据

        String result = iUserService.add(userModel);
//        req.setAttribute("result", result);

//        req.getRequestDispatcher("/html/Register.html").forward(req, resp);
        //        6.返回结果
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        resp.getWriter().println(jsonObject);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
